/*
Yao Ji 2015/5/12
*/
 var disableTouchmove =  function(e) {
                e.preventDefault()
               
            };

//用于开闭遮罩层
function set_cover_toggle(){
  	  $(".cover").css("height",document.documentElement.clientHeight < $("body").height() ? document.documentElement.clientHeight : $("body").height() );
      $(".cover").css("top",0);
      $("#setting_icon").click(function(){
            $(".cover").css("display","block");
            $(".cover").animate({left:"0"});
            document.body.addEventListener('touchmove',disableTouchmove);
      });

      $("#close_icon").click(function(){
            $(".cover").animate({left:"100%"},function(){
               $(".cover").css("display","none");
              document.body.removeEventListener('touchmove',disableTouchmove);
            });
      });
}

function initShareButton(){
    $("#shareBtn").click(function(){
           var clickedStatus = $(this).attr("clicked");
           if("no"==clickedStatus){
                $(this).attr("clicked","yes");
                $(".share-container").css("display","block");
                $(".share-container").animate({
                    height: 40
                  });
           }
           else{
                $(this).attr("clicked","no");
                $(".share-container").animate({
                    height: 0,
                },function(){
                  $(".share-container").css("display","none");
                });
                
           }
      });
}


function init_nav(){
        var index_selected = function(className){
        var num = $(className).length>0 ? $(className).find("a.selected").parent().index() : 0;
            return num;
        }(".swiper-container");
        var swiper = new Swiper('.swiper-container', {
            pagination: '.swiper-pagination',
            nextButton: '.swiper-button-next',
            prevButton: '.swiper-button-prev',
            slidesPerView: 3,
            slidesPerColumn: 1,
            paginationClickable: true,
            watchSlidesProgress : true,
            spaceBetween: 1,
            preventClicks: false,
            initialSlide: index_selected
        });
}


function beautifyContext(){
        $(".article-main").children().each(function(i,val){
              $(val).html($(val).html().replace(/&nbsp;/gi,''));
        });
        $(".article-main img").css("width","100%");
        $(".article-main p").css("font-size","20px");
        $(".article-main p").removeAttr("style");
        $(".article-main span").css("font-size","20px");
        $(".article-main strong").css("font-size","20px");
        $(".article-main h1").css("font-size","20px");
        $(".article-main h2").css("font-size","20px");
        $(".article-main h3").css("font-size","20px");
}


 

function loadMoreProducts(products){
       for(var i=0;i < products.length;i++ ){
    	   $("#clear-div").before('<div class="product-box"><div class="pic-box"><a href="/faxsun-info/product/view/'+products[i].id+'">'+
              '<img src="'+products[i].product.defaultImageUrl+'" /></a></div><a href="/faxsun-info/product/view/'+products[i].id+'" class="name"><strong>'+products[i].name+'</strong></a></div>'
              );
       }
                 
}

function loadMoreInfos(infos){
       for(var i=0;i < infos.length;i++ ){
           var imgUrl = "#";
           if(null!=infos[i].snapshot){
                imgUrl = infos[i].snapshot.original;
           } 
           $("#clear-div").before('<li ><div class="info-title-container"><a href="/faxsun-info/post/view/'+infos[i].id+'">'
              +'<strong class="title" >'+infos[i].title+'</strong></a></div><div class="info-pic-container"><a href="/faxsun-info/post/view/'+infos[i].id+'" style="background-image: url('+imgUrl+')">'
              +'</a></div><div class="info-summary-container"><a href="/faxsun-info/post/view/'+infos[i].id+'">'
              +'<span class="summary" fx="limit" num="50">'+ $(infos[i].summary).text() +'</span></a></div><div class="info-author-container"><span>'
              +infos[i].author.name+' | '+(infos[i].created) + '</span></div></li>');

       }

       $.each($('*[fx=limit]'), function(i) {
        $('*[fx=limit]').eq(i).limit($('*[fx=limit]').eq(i).attr('num'));
       });
                 
}

function pageScroll(){
    //把内容滚动指定的像素数（第一个参数是向右滚动的像素数，第二个参数是向下滚动的像素数）
    window.scrollBy(0,-100);
    //延时递归调用，模拟滚动向上效果
    scrolldelay = setTimeout('pageScroll()',500);
    //获取scrollTop值，声明了DTD的标准网页取document.documentElement.scrollTop，否则取document.body.scrollTop；因为二者只有一个会生效，另一个就恒为0，所以取和值可以得到网页的真正的scrollTop值
    var sTop=document.documentElement.scrollTop+document.body.scrollTop;
    //判断当页面到达顶部，取消延时代码（否则页面滚动到顶部会无法再向下正常浏览页面）
    if(sTop==0) clearTimeout(scrolldelay);
}


function hideOrShowTotop(){
    $('.toTopContainer').hide();
    $(window).scroll(function() {
        if ($(window).scrollTop() > 600)
            $('.toTopContainer').show();
        else
            $('.toTopContainer').hide();
    });
}

function showLoginPage(){
        $(".wrap-header").css("display","none");
        $("#login_form_container").css("display" ,"block");
        $("#register_form_container").css("display","none");
        $(".wrap-container").css("display","none");
        $(".login_register_box").css("display" ,"block");
}


var pro_thumbsup = function(url, followerId, uid, itemType) {

  if(followerId == '1'){
     var fingerprint = new Fingerprint({screen_resolution : true, ie_activex : true, canvas : true}).get();
     followerId = fingerprint;
  }
  
  $.post(url, {
    "followerId" : followerId,
    "uid" : uid,
    "itemType" : itemType
  }, function(data, status) {
    if (data.code == -2) {
      alert("请登录");
      showLoginPage();
    } else {
      $("#thumb-up-text").html("已点赞");
      $("#thumb-up-number").html("(" + data.count + ")");
      $("#pro_thumbsup_btn").attr("onclick",
          "javascript:pro_thumbsup_cancel('" + data.url + "','"
          + data.followerId + "','" + data.uid + "','"
          + data.itemType + "');return false;");
      $("#pro_thumbsup_i" ).removeClass("fa-thumbs-o-up");
      $("#pro_thumbsup_i" ).addClass("fa-thumbs-up");
      if (data.code == 101) {
        alert("您之前已经点过赞了哦。");
      } 
    }
  });
};

var pro_thumbsup_cancel = function(url, followerId, uid, itemType) {
  
  if(followerId == '1'){
     var fingerprint = new Fingerprint({screen_resolution : true, ie_activex : true, canvas : true}).get();
     followerId = fingerprint;
  }
  
  $.post(url, {
    "followerId" : followerId,
    "uid" : uid,
    "itemType" : itemType
  }, function(data, status) {
    if (data.code == -2) {
      alert("请登录");
      showLoginPage();
    } else {
      $("#thumb-up-text").html("点赞");
      $("#thumb-up-number").html("(" + data.count + ")");
      $("#pro_thumbsup_btn").attr("onclick",
          "javascript:pro_thumbsup('" + data.url + "','"
          + data.followerId + "','" + data.uid + "','"
          + data.itemType  + "');return false;");
      $("#pro_thumbsup_i").removeClass("fa-thumbs-up");
      $("#pro_thumbsup_i").addClass("fa-thumbs-o-up");
    }
  });
};

var pro_follow = function(url, followerId, uid, itemType) {
  $.post(url, {
    "followerId" : followerId,
    "uid" : uid,
    "itemType" : itemType
  }, function(data, status) {
    if (data.code == -2) {
      alert("请登录");
      showLoginPage();
     
    } else {
      if(itemType >= 2){
          $("#follow-text").html("已收藏");     
      }else{
          $("#follow-text").html("已关注");     
      }
      $("#follow-number").html("(" + data.count + ")");

      $("#pro_follow_btn").attr(
          "onclick",
          "javascript:pro_unfollow('" + data.url + "','"
              + data.followerId + "','" + data.uid + "','"
              + data.itemType  + "');return false;");
      $("#pro_follow_i").removeClass("fa-heart-o");
      $("#pro_follow_i").addClass("fa-heart");
      
      //reload for user center
      if(itemType == '0'){
         location.reload(); 
      }
    }
  });
};

var pro_unfollow = function(url, followerId, uid, itemType) {
  $.post(url, {
    "followerId" : followerId,
    "uid" : uid,
    "itemType" : itemType
  }, function(data, status) {
    if (data.code == -2) {
      alert("请登录");
      showLoginPage();
    } else {
       if(itemType >= 2){
          $("#follow-text").html("收藏");     
      }else{
          $("#follow-text").html("关注");     
      }
      $("#follow-number").html("(" + data.count + ")");
      
      $("#pro_follow_btn").attr(
          "onclick",
          "javascript:pro_follow('" + data.url + "','"
              + data.followerId + "','" + data.uid + "','"
              + data.itemType +  "');return false;");
      $("#pro_follow_i" ).removeClass("fa-heart");
      $("#pro_follow_i" ).addClass("fa-heart-o");
      
      //reload for user center
      if(itemType == '0'){
         location.reload(); 
      }
    }
  });
}



function limitContext(object){
    var originalLength =  $(object).attr("context").length;
    var limitNum = $(object).attr("limitNum");
    var str = $(object).attr("context");
    if(originalLength > limitNum){
        var limitedStr = str.substring(0, limitNum) + "..."
        var $contentContainer = $(object).find(".content");
        $contentContainer.text(limitedStr);
         var $expandSpan = $("<strong >[详细]</strong>");
         var $collapseSpan = $("<strong style='display:none' >[折起]</strong>");
         $expandSpan.click(function(){
             $contentContainer.html(str);
             $expandSpan.css("display","none");
             $collapseSpan.removeAttr("style");
         });
         $collapseSpan.click(function(){
             $contentContainer.html(limitedStr);
             $collapseSpan.css("display","none");
             $expandSpan.removeAttr("style");
         });

         $(object).append($expandSpan);
         $(object).append($collapseSpan);
    }
}
$.each($('*[fx=limit-context]'), function(i) {
    limitContext($('*[fx=limit-context]').eq(i));
});


function initLiveBtn(){
    $("#ctg_live_btn").click(function(){
           var clickedStatus = $("#ctg_live_btn").attr("clicked");
           if(undefined==clickedStatus||"no"==clickedStatus){
                $(this).attr("clicked","yes");

                var el = $('.liveShowList'),
                autoHeight = el.css('height', 'auto').height();
                $(".liveShowList").css("display","block");
                el.height(0).animate({height: autoHeight});
           }
           else{
                $(this).attr("clicked","no");
                $(".liveShowList").animate({
                    height: 0
                },function(){
                  $(".liveShowList").css("display","none");
                });
                
           }
    });
}

function startLoadVideo(elem){
     $(elem).removeAttr("onclick");
     var $video = $("<video  loadstart='alert(12)' controls='controls' autoplay='autoplay'><source  type='video/mp4' src='"+ $(elem).attr("videoSrc")+"'/>Your browser does not support HTML5 video.</video>");
     $(elem).empty();
     $(elem).append($video);

}


function initDateTabNav(){
   $(".date-tab-container span.tab").each(function(index,elem){
            $(elem).on("click",function(){
              $(elem).parent().children("span.tab").css({"background-color":"#d7e4ed","color":"black"});
              $(elem).css({"background-color":"#0087e2","color":"white"});
              var val = $(this).attr("date-val");
              if($("span[data-date="+val+"].qDate").eq(0).parents(".timeline").offset()!=undefined){
                   var spanTop = $("span[data-date="+val+"].qDate").eq(0).parents(".timeline").offset().top ;
                    $("html,body").animate({
                              scrollTop: spanTop -$(window).height()*0.1 + "px"
                          },500);
              }
             
              
            });
        })
}


function scrollToCommentsContainer(){
   var commentsContainerOffsetTop = document.getElementById("commentsContainer").offsetTop;
       $("html,body").animate({
                              scrollTop: commentsContainerOffsetTop
                          },"fast");
}

function  showMsgHintBox(){
   $(window).scroll(function () {
                var commentsContainerOffsetTop = document.getElementById("commentsContainer").offsetTop;
                var commentsContainerHeight = document.getElementById("commentsContainer").height;
                var scrollTop = $(window).scrollTop();

             //   console.log("commentsContainerOffsetTop "+commentsContainerOffsetTop+" scrollTop "+scrollTop+" height "+$(window).height());
                if ((commentsContainerOffsetTop - $(window).height()*0.9 + 70 <= scrollTop)){
                      $(".leaveMsgHintContainer").css("display","block");
                        // $(".leaveMsgHintContainer").animate({'bottom' : '0px'},"fast");
                }
                else{
                 $(".leaveMsgHintContainer").css("display","none");

                    // $(".leaveMsgHintContainer").animate({'bottom' : '-50px'},"fast");
                }


            });

   $("#comment_btn_mobile").click(function(){
        scrollToCommentsContainer();
        $(".leaveMsgInputBox").removeAttr("isReply");
        $(".leaveMsgInputBox #msgInput").removeAttr("placeholder");
   
   });


    $("#leave-msg-hint-close").click(function(){
        $(".leaveMsgHintContainer").css("display","none");

       //  $(".leaveMsgHintContainer").animate({'bottom' : '-50px'},"fast");
    });

     $(".hint-context").click(function(){
       $(".leaveMsgInputBox").css("display","block");
        $(".leaveMsgHintContainer").css("display","none");
         // $(".leaveMsgInputBox").animate({'bottom' : '0px'},"fast");
         // $(".leaveMsgHintContainer").animate({'bottom' : '-50px'},"fast");
    });

     $("#cancelReplyMobile").click(function(){
        $(".leaveMsgInputBox").css("display","none");
          //  $(".leaveMsgInputBox").animate({'bottom' : '-50px'},"fast");
     });


    loadComments();
    

}

function loadComments(){

      var prefix = "";
      if (window.location.href.indexOf('faxsun-info-web') > -1) {
        prefix += "/faxsun-info-web";
      } else if (window.location.href.indexOf('faxsun-info') > -1) {
        prefix += "/faxsun-info";
      }

     var product_id = $('#product_id').val();
     var totalPageNum = 1;

     //计算总点评数
     if ($('span#comment-number').length > 0) {
        if (product_id !== '' && product_id !== undefined) {
          $.get(prefix + '/comment/list/' + product_id + '?type=0&pn=1')
              .done(
                  function(data) {
                    $(".commentsContainer").empty();
                    $('span#comment-number').text(
                        '(' + data.totalCount + ')');

                    loadCommentsList(prefix,data.results);

                    totalPageNum = data.totalCount / 10 + 1;
                     if(totalPageNum > 1){
                          for(var i=2;i<=totalPageNum;i++){
                              $.get(prefix + '/comment/list/' + product_id + '?type=0&pn='+i)
                                .done(
                                    function(data) {
                                        loadCommentsList(prefix,data.results);
                                    }).fail(
                                    function() {

                                    });
                          }

                    }

                  }).fail(
                    function() {
                      $('span#comment-number').text(
                          '(' + 0 + ')');
                  });
        }
    };
   
    
    

}


function loadCommentsList(prefix,results){
  for(var i=0;i<results.length;i++){

     var $comment = $('<div class="commentContainer"><div class="comentUsrContainer"><img class="portrait" src="'+prefix+results[i].author.avatar+'"/>'
                    +'<span class="name">'+results[i].author.name+'</span>'
                    +'<span class="time">'+results[i].created+'</span>'
                    +'<span class="reply" onclick="showReplyBox(this)" author_name="'+results[i].author.name+'" commentId="'+results[i].id+'">[回复]</span></div>'
                    +'<div class="comentContextContainer">'+results[i].content+'</div> </div>');
  
    $(".commentsContainer").append($comment);

  }

}


function showReplyBox(elem){
    var $leaveMsgInputBox = $(".leaveMsgInputBox");
    $leaveMsgInputBox.css("display","block");
    $(".leaveMsgHintContainer").css("display","none");

      // $leaveMsgInputBox.animate({'bottom' : '0px'},"fast");
      // $(".leaveMsgHintContainer").animate({'bottom' : '-50px'},"fast");

    $(".leaveMsgInputBox #msgInput").attr("placeholder","回复："+$(elem).attr("author_name"));
    $leaveMsgInputBox.attr({"isReply":"yes","author_name":$(elem).attr("author_name"),"commentId":$(elem).attr("commentId")});

}

function initCommentInput(){
     $(".leaveMsgInputBox #msgSendMobile").click(function(){
              if(""==$("#msgInput").val()){
                    alert("输入不能为空");
              }
              else{
                    $leaveMsgInputBox = $(".leaveMsgInputBox");
                    var isReply =  $leaveMsgInputBox.attr("isReply");
                    if(undefined==isReply||"no"==isReply){
                        //直接留言
                        leaveCommentDirectly('/faxsun-info/comment/post',0,$("#msgInput").val(),$leaveMsgInputBox.attr("product_id"));
                    }
                    else{
                        //回复他人的留言
                        relpyComment('/faxsun-info/comment/post/reply',0,$("#msgInput").val(), $leaveMsgInputBox.attr("product_id"),$leaveMsgInputBox.attr("commentId"),$leaveMsgInputBox.attr("author_name"));
                     
                    }
                    $("#msgInput").val("");
                   $(".leaveMsgInputBox").css("display","none");

                       // $(".leaveMsgInputBox").animate({'bottom' : '-50px'},"fast");


              }
              

     });
}

function leaveCommentDirectly(url,type,text,toId){
  $.ajax({
        type : "POST",
        url : url, 
        data : {
           "text" : text,
           "type" : type,
           "toId" : toId
          },
          success : function(data) {
            var ret = JSON.parse(data);
          if (ret.code < 0) {
            alert(ret.message);
            if (ret.code == -2) {
              // 未登录
             // $('#trigger-overlay').trigger('click');
               showLoginPage();
            }
          } else if (ret.code == 0) {
            if(ret.data.type == 2){
                loadComments();

            }else{
                loadComments(); 
                scrollToCommentsContainer();
            }
          } else {
            alert(ret.message);
          }
        }
    });
}

function relpyComment(url,type,text,toId,commentId,commentToUserName){
     $.ajax({
        type : "POST",
        url : url, 
        data : {
           "text" : text,
           "type" : type,
           "toId" : toId,
           "commentId" : commentId,
           "commentToUserName" : commentToUserName
          },
          success : function(data) {
            var ret = JSON.parse(data);
          if (ret.code < 0) {
            alert(ret.message);
            if (ret.code == -2) {
              // 未登录
             // $('#trigger-overlay').trigger('click');
               showLoginPage();
            }
          } else if (ret.code == 0) {
            if(ret.data.type == 2){
                loadComments();

            }else{
                loadComments(); 
                scrollToCommentsContainer();
            }
          } else {
            alert(ret.message);
          }
        }
    });
}


function initExpandableArticleList(){
  if($(".articleVerticalList > .article").size()>2){
            $.each($(".articleVerticalList > .article"), function(i) {
                if(i>1){
                    $(this).css("display","none");
                }
            });

            $("#avlExpandAndCollapse").css("display","block");
            $("#avlExpandAndCollapse").click(function(){
                  if("collapsed"==$(this).attr("status")){
                        $.each($(".articleVerticalList > .article"), function(i) {
                            $(this).css("display","block");
                        });
                        $(this).attr("status","expanded");
                        $(this).children("span").text("折起");
                  }
                  else{
                        $.each($(".articleVerticalList > .article"), function(i) {
                             if(i>1){
                                  $(this).css("display","none");
                              }
                        });
                        $(this).attr("status","collapsed");
                        $(this).children("span").text("展开");

                  }
            });
        }





}

